""" 
Compiles a file of all known classes and pet types. 

Options:
	-path "C:\My Stuff\masterresourceunits.dat"
		Specifies a different path to use for masterresourceunits.dat. If not specified,
		the default will be used: 
			%appdata%\runic games\torchlight\masterresourceunits.dat
		
	-out myvals.cfg
		Specifies an output file to dump the values to. If not specified, a "builtins.cfg" file
		will be created.

	-errlog builtins.err
		Redirects errors to the given file.
"""

import os
import sys
import codecs
from svtutil import arg, indexof

el = arg(sys.argv, '-errlog')
if el is not None:
	sys.stderr = open(el, 'w')

appdata = os.environ['APPDATA']

masterpath = arg(sys.argv, '-path')
outpath = arg(sys.argv, '-out', 'builtins.cfg')

if masterpath is None:
	if appdata is None or len(appdata)==0:
		raise Error('could not find %APPDATA% environment variable')
	masterpath = os.path.join(appdata, 'runic games/torchlight/masterresourceunits.dat')

if not os.path.exists(masterpath):
	raise Error('could not find %s, run Torchlight and try again' % masterpath)

print 'Reading %s, this may take a few moments...' % os.path.basename(masterpath)

resources = codecs.open(masterpath, 'rb', encoding='UTF-16')

MONSTERS = '[MONSTERS]'
PLAYERS = '[PLAYERS]'
reading = None

DISPLAYNAME1 = '<TRANSLATE>DISPLAYNAME:'
DISPLAYNAME2 = '<STRING>DISPLAYNAME:'
DATFILE = '<STRING>DATFILE:'
GUID = '<STRING>UNIT_GUID:'
UNITTYPE = '<STRING>UNITTYPE:'
pets = []
petsStd = []
lastPet = None
classes = []
classesStd = []
vals = 0
count = 0
STD_PETS = ['Cat', 'Dog', 'Ferret', 'Imaginary']
STD_CLASSES = ['Alchemist', 'Destroyer', 'Vanquisher']

for line in resources:
	count += 1
	line = line.strip()
	if len(line)==0:
		pass
	elif line[0] == '[':
		reading = line
		vals = 0
		#reading new monster, set up a new pet
		if reading == MONSTERS:
			lastPet = {}
	elif reading == MONSTERS:
		if line.startswith(DATFILE):
			if lastPet.get('isPet') is None:
				lastPet['isPet'] = 'pet' in os.path.basename(line).lower()
			vals += 1
		elif line.startswith(UNITTYPE):
			if 'PET' != line[len(UNITTYPE):]:
				lastPet['isPet'] = False
			vals += 1
		elif line.startswith(DISPLAYNAME1) or line.startswith(DISPLAYNAME2):
			st = DISPLAYNAME1 if line.startswith(DISPLAYNAME1) else DISPLAYNAME2
			lastPet['name'] = line[len(st):]
			vals += 1
		elif line.startswith(GUID):
			lastPet['guid'] = line[len(GUID):]
			vals += 1
		if vals>=4:
			isStd = lastPet['name'] in STD_PETS
			if lastPet.get('isPet') or isStd:
				p = petsStd if isStd else pets
				p.append(lastPet)
				reading = None
	elif reading == PLAYERS:
		if line.startswith(DISPLAYNAME1) or line.startswith(DISPLAYNAME2):
			st = DISPLAYNAME1 if line.startswith(DISPLAYNAME1) else DISPLAYNAME2
			n = line[len(st):]
			if n!='BasePlayer':
				isStd = n in STD_CLASSES
				c = classesStd if isStd else classes
				c.append(n)
			vals += 1
		if vals >= 1:
			reading = None
		
out = open(outpath, 'w')
out.write('#generated by getbuiltins\n')
out.write('[PET_TYPES]\n')
petsStd.extend(pets)
for p in petsStd:
	k, v = p['guid'], p['name']
	out.write("%s:%s\n" % (k, v))

out.write('\n[CLASSES]\n')
classesStd.extend(classes)
for c in classesStd:
	out.write('%s\n' % c)
out.close()